﻿using System;

using System.Collections;

using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Transactions;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using Global.Class.Library;
using BusinessLogicLayer;
using DataTransferObject;
using DataAccessLayer;
using DataAccessLayer.ImportDataSetTableAdapters;


using System.Globalization;
using BrightIdeasSoftware;
using Equin.ApplicationFramework;


using OfficeExcel = Microsoft.Office.Interop.Excel;


namespace PresentationLayer
{
    public partial class InMarketImport : Form, IMergeToolStrip, ICallToolStrip
    {

        #region <Implement Interface>

        public event PropertyChangedEventHandler PropertyChanged;

        private void NotifyPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }

        public GlobalEnum.TaskID TaskID
        {
            get { return GlobalEnum.TaskID.InMarketImport; }
        }


        public ToolStrip ChildToolStrip
        {
            get
            {
                return this.toolStripChildForm;
            }
            set
            {
                this.toolStripChildForm = value;
            }
        }





        #region Context toolbar


        public bool IsDirty
        {
            get { return false; }
        }

        public bool IsValid
        {
            get { return false; }
        }

        public bool Closable
        {
            get { return true; }
        }

        public bool Loadable
        {
            get { return true; }
        }

        public bool Newable
        {
            get { return true; }
        }

        public bool Editable
        {
            get { return false; }
        }

        public bool Deletable
        {
            get { return this.ImportBatchID > 0; }
        }

        public bool Importable
        {
            get { return true; }
        }

        public bool Exportable
        {
            get { return true; }
        }

        public bool Verifiable
        {
            get { return false; }
        }

        public bool Unverifiable
        {
            get { return false; }
        }

        public bool Printable
        {
            get { return false; }
        }

        public bool Searchable
        {
            get { return true; }
        }


        /// <summary>
        /// Edit Mode: True, Read Mode: False
        /// </summary>
        private bool editableMode;
        public bool EditableMode { get { return this.editableMode; } }
        /// <summary>
        /// This reverse of the EditableMode
        /// </summary>
        public bool ReadonlyMode { get { return !this.editableMode; } }

        /// <summary>
        /// Set the editableMode
        /// </summary>
        /// <param name="editableMode"></param>
        private void SetEditableMode(bool editableMode)
        {
            if (this.editableMode != editableMode)
            {
                this.editableMode = editableMode;
                this.NotifyPropertyChanged("EditableMode");

            }
        }


        private void CancelDirty(bool restoreSavedData)
        {
            try
            {
                this.SetEditableMode(false);
            }
            catch (Exception exception)
            {
                throw exception;
            }
        }



        #endregion Context toolbar



        #region ICallToolStrip

        public void Escape()
        {
            if (this.EditableMode)
            {
                if (this.IsDirty)
                {
                    DialogResult dialogResult = MessageBox.Show(this, "Do you want to save your change?", "Warning", MessageBoxButtons.YesNoCancel);
                    if (dialogResult == DialogResult.Yes)
                    {
                        this.Save();
                        if (!this.IsDirty) this.CancelDirty(false);
                    }
                    else if (dialogResult == DialogResult.No)
                    {
                        this.CancelDirty(true);
                    }
                    else
                        return;
                }
                else
                    this.CancelDirty(false);
            }
            else
                this.Close(); //Unload this module
        }

        //Can phai xem lai trong VB de xem lai this.SetEditableMode () khi can thiet

        public void Loading()
        {
            this.GetMasterList();
        }

        public void New()
        {
            this.SetEditableMode(true);
        }

        public void Edit()
        {
            this.SetEditableMode(true);
        }

        public void Save()
        {
        }

        public void Delete()
        {
            DialogResult dialogResult = MessageBox.Show(this, "Are you sure you want to delete " + this.ImportFile + "?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Stop);
            if (dialogResult == DialogResult.Yes)
            {
                try
                {
                    TimeSpan timeout = TimeSpan.FromMinutes(45);
                    using (TransactionScope transactionScope = new TransactionScope(TransactionScopeOption.Required, timeout))
                    {
                        //Set lObj = New clsTransInMarketMaster: Set lRec = ADORECNEW
                        //lRec.Open "SELECT DISTINCT InMarketDate FROM InMarketMaster WHERE ImportBatchID = "  + this.ImportBatchID, ClassConn
                        //While Not lRec.BOF And Not lRec.EOF
                        //    lObj.InMarketDate = lRec.Fields("InMarketDate")
                        //    If Not lObj.Editable Then pfMessageBox ENothing, "Can not delete this transaction." & Chr(13) & "Please delete sales performance in order to try again.", EStop: GoTo ERR_HANDLER
                        //    lRec.MoveNext
                        //Wend

                        SQLDatabase.ExecuteNonQuery("DELETE FROM InMarketDetail WHERE InMarketID IN (SELECT InMarketID FROM InMarketMaster WHERE ImportBatchID = " + this.ImportBatchID + ")");
                        SQLDatabase.ExecuteNonQuery("DELETE FROM InMarketMaster WHERE ImportBatchID = " + this.ImportBatchID);
                        SQLDatabase.ExecuteNonQuery("DELETE FROM ListImportBatchMaster WHERE ImportBatchID = " + this.ImportBatchID);
                        SQLDatabase.ExecuteNonQuery("DELETE FROM ListCustomerNameTracking WHERE ImportBatchID = " + this.ImportBatchID);

                        SQLDatabase.ExecuteNonQuery("UPDATE ListCustomerNameTracking SET FirstChangeLog = 0 ");
                        SQLDatabase.ExecuteNonQuery("UPDATE ListCustomerNameTracking SET FirstChangeLog = 1 WHERE CustomerID IN (SELECT CustomerID FROM ListCustomerNameTracking GROUP BY CustomerID HAVING COUNT(SerialID) = 1) ");

                        transactionScope.Complete();
                    }

                    this.GetMasterList();
                }
                catch (Exception exception)
                {
                    GlobalExceptionHandler.ShowExceptionMessageBox(this, exception);
                }
            }
        }

        public void Import()
        {
            this.ImportExcel();
        }

        public void Export()
        {
            try
            {
                DataTable dataTableExport;
                dataTableExport = this.dataListViewMaster.DataSource as DataTable;
                if (dataTableExport != null) CommonFormAction.Export(dataTableExport);
            }
            catch (Exception exception)
            {
                GlobalExceptionHandler.ShowExceptionMessageBox(this, exception);
            }
        }

        public void Verify()
        {
            MessageBox.Show("Verify");
        }

        public void Print(PrintDestination printDestination)
        {
            MessageBox.Show("Print");
        }

        public void SearchText(string searchText)
        {
            CommonFormAction.OLVFilter(this.dataListViewMaster, searchText);
        }

        #endregion


        #endregion <Implement Interface>









        #region <Storage>


        #endregion <Storage>


        public InMarketImport()
        {
            try
            {
                InitializeComponent();

                if (GlobalVariables.shouldRestoreProcedure) RestoreProcedure();

            }
            catch (Exception exception)
            {
                GlobalExceptionHandler.ShowExceptionMessageBox(this, exception);
            }
        }


        private void InMarketImport_Load(object sender, EventArgs e)
        {
            try
            {
                InitializeCommonControlBinding();

                InitializeDataGridBinding();

                InitializeReadOnlyModeBinding();
            }
            catch (Exception exception)
            {
                GlobalExceptionHandler.ShowExceptionMessageBox(this, exception);
            }
        }


        #region <InitializeBinding>


        private void InitializeCommonControlBinding()
        {

        }

        private int ImportBatchID { get; set; }
        private string ImportFile { get; set; }

        private InMarketImportListingTableAdapter listingTableAdapter;
        protected InMarketImportListingTableAdapter ListingTableAdapter
        {
            get
            {
                if (listingTableAdapter == null) listingTableAdapter = new InMarketImportListingTableAdapter();
                return listingTableAdapter;
            }
        }


        private void GetMasterList()
        {
            foreach (OLVColumn olvColumn in dataListViewMaster.Columns) { olvColumn.Renderer = null; }

            DataTable inMarketImportListing = this.ListingTableAdapter.GetData(GlobalVariables.GlobalOptionSetting.LowerFillterDate.AddMonths(-3), GlobalVariables.GlobalOptionSetting.UpperFillterDate);
            inMarketImportListing.TableName = "InMarketImportListing";

            //DataSet bindingDataSet = new DataSet();
            //bindingDataSet.Tables.Add(inMarketImportListing);

            this.dataListViewMaster.AutoGenerateColumns = false;
            this.dataListViewMaster.DataSource = inMarketImportListing;


        }

        private void InitializeDataGridBinding()
        {

            this.GetMasterList();


        }

        private void InitializeReadOnlyModeBinding()
        {
            List<Control> controlList = GlobalStaticFunction.GetAllControls(this);

            foreach (Control control in controlList)
            {
                //if (control is TextBox) control.DataBindings.Add("Readonly", this, "ReadonlyMode");
                if (control is TextBox) control.DataBindings.Add("Enabled", this, "EditableMode");
                else if (control is ComboBox || control is DateTimePicker) control.DataBindings.Add("Enabled", this, "EditableMode");
                else if (control is DataGridView)
                {
                    //control.DataBindings.Add("Readonly", this, "ReadonlyMode");
                    //control.DataBindings.Add("AllowUserToAddRows", this, "EditableMode");
                    //control.DataBindings.Add("AllowUserToDeleteRows", this, "EditableMode");
                }
            }

            this.dataListViewMaster.DataBindings.Add("Enabled", this, "ReadonlyMode");
        }

        #endregion <InitializeBinding>




        private void dataListViewMaster_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                ObjectListView objectListView = (ObjectListView)sender;
                DataRowView row = (DataRowView)objectListView.SelectedObject;

                if (row != null)
                {
                    int importBatchID;

                    if (int.TryParse(row.Row["ImportBatchID"].ToString(), out importBatchID))
                        this.ImportBatchID = importBatchID;
                    else this.ImportBatchID = 0;

                    this.ImportFile = row.Row["ImportFile"].ToString();
                }
                else { this.ImportBatchID = 0; this.ImportFile = ""; }

                this.NotifyPropertyChanged("ImportBatchID");
            }
            catch (Exception exception)
            {
                GlobalExceptionHandler.ShowExceptionMessageBox(this, exception);
            }
        }









        #region Import Excel

        private void ImportExcel()
        {
            try
            {
                OpenFileDialog openFileDialog = new OpenFileDialog();
                openFileDialog.Filter = "Excel File (.xlsx)|*.xlsx";

                if (openFileDialog.ShowDialog() == DialogResult.OK)
                {
                    Global.Class.Library.GlobalVariables.DistributorID = 0;
                    DialogImport03 dialogImport03 = new DialogImport03(OleDbDatabase.MappingTaskID.InMarket, openFileDialog.FileName);

                    if (dialogImport03.ShowDialog() == DialogResult.OK)
                    {
                        dialogImport03.Dispose();


                        DialogImport06 dialogImport06 = new DialogImport06(OleDbDatabase.MappingTaskID.InMarket, openFileDialog.FileName);

                        if (dialogImport06.ShowDialog() == DialogResult.OK)
                        {
                            dialogImport06.Dispose();

                            DialogImport09 dialogImport09 = new DialogImport09(OleDbDatabase.MappingTaskID.InMarket, openFileDialog.FileName, GlobalEnum.EIColumnID.EICommodityID, GlobalEnum.EIColumnID.EINoneID);

                            if (dialogImport09.ShowDialog() == DialogResult.OK)
                            {
                                dialogImport09.Dispose();

                                dialogImport09 = new DialogImport09(OleDbDatabase.MappingTaskID.InMarket, openFileDialog.FileName, GlobalEnum.EIColumnID.EIAddressAreaID, GlobalEnum.EIColumnID.EINoneID);

                                if (dialogImport09.ShowDialog() == DialogResult.OK)
                                {
                                    dialogImport09.Dispose();

                                    dialogImport09 = new DialogImport09(OleDbDatabase.MappingTaskID.InMarket, openFileDialog.FileName, GlobalEnum.EIColumnID.EICustomerTypeID, GlobalEnum.EIColumnID.EINoneID);

                                    if (dialogImport09.ShowDialog() == DialogResult.OK)
                                    {
                                        dialogImport09.Dispose();

                                        dialogImport09 = new DialogImport09(OleDbDatabase.MappingTaskID.InMarket, openFileDialog.FileName, GlobalEnum.EIColumnID.EICustomerChannelID, GlobalEnum.EIColumnID.EINoneID);

                                        if (dialogImport09.ShowDialog() == DialogResult.OK)
                                        {
                                            dialogImport09.Dispose();

                                            dialogImport09 = new DialogImport09(OleDbDatabase.MappingTaskID.InMarket, openFileDialog.FileName, GlobalEnum.EIColumnID.EICustomerID, GlobalEnum.EIColumnID.EIAddressAreaID);

                                            if (dialogImport09.ShowDialog() == DialogResult.OK)
                                            {
                                                dialogImport09.Dispose();

                                                if (Global.Class.Library.GlobalVariables.ImportNextStep == 1)
                                                {
                                                    this.Loading();
                                                    MessageBox.Show(this, "Congratulation!" + "\r\n" + "\r\n" + "File: " + openFileDialog.FileName + " is imported successfull! Please press OK to finish.", "ERmgrUIP", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                                }

                                            }

                                        }


                                    }


                                }
                            }



                        }


                    }
                }

            }
            catch (Exception exception)
            {
                GlobalExceptionHandler.ShowExceptionMessageBox(this, exception);
            }


        }



        private void RestoreProcedure()
        {
            string queryString;

            queryString = "     @LowerFillterDate DateTime, @UpperFillterDate DateTime " + "\r\n";
            queryString = queryString + " WITH ENCRYPTION " + "\r\n";
            queryString = queryString + " AS " + "\r\n";
            queryString = queryString + "       SELECT      LEFT(CONVERT(char(10), ListImportBatchMaster.ImportDate, 111), 7) AS ImportMonth, ListImportBatchMaster.ImportDate, ListImportBatchMaster.ImportBatchID, ListImportBatchMaster.ImportFile, ListImportBatchMaster.InvoiceCount, ListImportBatchMaster.EmployeeID, (SELECT COUNT(ImportBatchID) AS CountCustomerChange FROM ListCustomerNameTracking WHERE ListCustomerNameTracking.FirstChangeLog = 0 AND ListCustomerNameTracking.ImportBatchID = ListImportBatchMaster.ImportBatchID) AS CountCustomerChange  " + "\r\n";

            queryString = queryString + "       FROM        ListImportBatchMaster " + "\r\n";
            queryString = queryString + "       WHERE       ListImportBatchMaster.ImportDate >= @LowerFillterDate AND ListImportBatchMaster.ImportDate <= @UpperFillterDate " + "\r\n";

            SQLDatabase.CreateStoredProcedure("InMarketImportListing", queryString);
        }


        #endregion Import Excel











    }




}
